/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.worsik.vypocty.topeni.tepelneztraty.dao;

import static cz.worsik.vypocty.topeni.tepelneztraty.dao.SqlStatements.SELECT_FROM_SYSTABLES;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Trida slouzi pro inicializaci databaze, pokud neni v databazi schema pro
 * aplikaci. Existenci overuje pres existenci tabulky t_transakce - zjistuje
 * selectem do sys.systables <br/>
 * 
 * @version $Id: InicializaceDbDao.java $
 * @author mruzek
 */
public class InicializaceDbDao implements IInicializaceDbDao {
    private static final Logger log = LoggerFactory
            .getLogger(InicializaceDbDao.class);
	
	/** "ORM" integrace (Spring JdbcTemplate) */
    protected JdbcTemplate jt;

	public void setJt(JdbcTemplate jt) {
		this.jt = jt;
	}

    @Override
    public void inicializovat() {

        List<Map<String, Object>> list = jt.queryForList(SELECT_FROM_SYSTABLES);
        if (list.isEmpty()) {
			log.debug("Schema neexistuje, vytvarim DB ze schematu.");
            String script = "";
            try {
                
                InputStream is = getClass().getResourceAsStream("/schema.sql");
                
                script = convertStreamToString(is);
                is.close();
                
            } catch (IOException e) {                
                e.printStackTrace();
                System.exit(1);
            }
            
            while (script.indexOf(";") != -1) {
				String sql = script.substring(0, script.indexOf(";"));
                jt.execute(sql);
                script = script.substring(script.indexOf(";") + 1);
                
            }
        }
		else
			log.debug("Schema existuje, neni treba vytvaret.");
    }
    
    private String convertStreamToString(InputStream is) throws IOException {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        if (is != null) {
            StringBuilder sb = new StringBuilder();
            String line;

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                is.close();
            }
            return sb.toString();
        } else {        
            return "";
        }
    }
}
